var client = require("../DAOImpl/mongodb");
var dataConfig = require("../config/database.json");
var host = dataConfig.host;
var database = dataConfig.db;
var db = new client(host, database);
var status = require("../config/status.json");
var notification = require('../private/notification');
var googlemap = require('../private/googleService/service');
var findDrivers = require('../private/findDrivers');
var ObjectID = require('mongodb').ObjectID;

function sleep(milliSecond) {
	var startTime = new Date().getTime();
	console.log(startTime);
	while (new Date().getTime() <= milliSecond + startTime) {
	}
	console.log(new Date().getTime());
}
/*
 * @req.body cus_lat cus_lng cus_id {"cus_lat":
 * 31.202818,"cus_lng":121.557706,"cus_id":1}
 */
function bookNow(req, res, next) {
	console.log('bookNow');
	var cus_id = req.body.cus_id;
	var cus_lat = req.body.cus_lat;
	var cus_lng = req.body.cus_lng;
	var cus_options=req.body.cus_options;
	
	var order_id = "";
	var orderSelector = new Object();
	var result = new Object();
	var selector = new Object();
	var info = new Object();
	var forIndex = cus_id+"1";
	info.cus_id = req.body.cus_id;
	info.status = status.ORDERSTATUS.CUSTOMERREQUEST.VALUE;
    info.type = status.ORDERTYPE.BOOKNOW;
    info.cus_lat = req.body.cus_lat;
    info.cus_lng = req.body.cus_lng;
	info.forIndex = forIndex;
	info.driverspool = new Array();
	
	db.insertIndex(dataConfig.col_order, info, {"forIndex" : 1}, function(err1, orderInfo) {// 4
		if (err1) {
			console.log(err1);
			result.status = status.SYSTEMERROR.VALUE;
			res.send(result);
			} else {
				order_id = orderInfo[0]._id;
				orderSelector = {"_id" : order_id};
                console.log(order_id);                                             //booknow process
				if(cus_options == 1){
				                                                     	//1: query--findDrivers
					var query = findDrivers.findCondition(cus_lat, cus_lng);
					db.find(dataConfig.col_driver,query,function(err2, doc1) {
						if (err2) {
							console.log(err2);
							result.status = status.SYSTEMERROR.VALUE;
							res.send(result);
							} else {
								db.findOne(dataConfig.col_customer,{'cus_id' : cus_id},function(err0,doc0){
									if(err0){
										console.log(err0);
										result.status = status.SYSTEMERROR.VALUE;
										res.send(result);
									}
									else{
										for (index in doc1) {
											var dri_id = doc1[index].dri_id;
											var message = new Object();
											message.push_kind = cus_options;
											message.cus_lat = cus_lat;
											message.cus_lng = cus_lng;
											message.cus_id = cus_id;
											message.order_id = order_id;
											message.credit = doc0.cus_credit;
											message.cus_name = doc0.cus_nickname;
											message.location = 'central park'
											var notifi = new notification(dri_id,message,function(err3,req,res,data) {
												console.log('notification to proper driver : '+ data);
												if (err3) {
													console.log(err3+ 'notification err');
													result.status = status.SYSTEMERROR.VALUE;
													res.send(result);
													} else {
														console.log('notification to proper driver : '+ data);
														// ---------- unfinished!find?
														}
												});
											}
										setTimeout(
												function() {
													db.findOne(dataConfig.col_order,orderSelector,function(err4,doc2) {
														if (err4) {													
															console.log(err4+ 'find driverspool err');
															result.status = status.SYSTEMERROR.VALUE;
															res.send(result);
															}
														else if(doc2.driverspool.length == 0){
															result.status = status.SYSTEMERROR.VALUE;
															result.message = 'NO DRIVER';
/*															db.remove(dataConfig.col_order,orderSelector,function(err9,doc){
																if(err9||err10){
																	console.log(err9 + ' err');
																	result.status = status.SYSTEMERROR.VALUE;
																	res.send(result);
																}else{
																	console.log('remove ok');
																	console.log('No driver');
																	res.send(result);
																}
															});*/
															console.log('No driver');
															res.send(result);
														}
														else {
//															console.log(doc2);
															findDrivers.getNeareastDri(
																	doc2.driverspool,function(err5,infoPool) {
																		if (err5) {
																			console.log(err5+ 'find nearest err');
																			result.status = status.SYSTEMERROR.VALUE;
																			res.send(result);
																			} else {
																				
																				result.dri_info = infoPool.dri_info;
																				result.distance = infoPool.distance;
																				result.saveTime = infoPool.duration;
																				result.status = status.SUCCESS.VALUE;
																				/* NoTIFI FINAL RESULT TO CUSTOMER*/
																				
																				message.dri_id = infoPool.dri_info.dri_id;
																				message.credit = infoPool.dri_info.dri_credit;
																				message.distance = infoPool.distance;
																				message.saveTime = infoPool.duration;
																				var notifi2 = new notification(cus_id , message, function(err3,req,res,data) {
																					console.log('notification is to customer final : '+message);
																					if (err3) {
																						console.log(err3+ 'notification err');
																						result.status = status.SYSTEMERROR.VALUE;
																						res.send(result);
																						} else {
																							console.log('notification is to customer final : '+message);
																							}
																					});
																			//	console.log(result);
																				res.send(result);
																				}
																		});
															}
														});
													}, 20000);
									}
								
								});
								                                           //2:--notification

								}
						});
				}else{
					//fastest driver
				}
// send notification to drivers which in the square between (lat-50.0,lon-50.0) and (lat+50.0,lon+50.0);
				
				}//
		});// 4
	return next;
}

/*
 * @req.body: cus_id {'cus_id': '1'}, page
 */

function showOrder(req, res, next) {
	var result = new Object();
	var query1 = new Object();
	query1.cus_info = new Object();
	query1.cus_info._id = req.body.cus_id;
	query1.status = status.ORDERSTATUS.WAITING.VALUE;
	db.find(dataConfig.col_order,query1,function(err1, doc_waiting) {
		if (err1) {
			result.status = status.SYSTEMERROR.VALUE;
			res.send(result);
			} else {
				var query2 = new Object();
				query2.cus_info = new Object();
				query2.cus_info._id = req.body.cus_id;
				query2.status = status.ORDERSTATUS.CUSTOMERACCEPT.VALUE;
				db.find(dataConfig.col_order,query2,function(err3, doc_success) {
					if (err3) {
						result.status = status.SYSTEMERROR.VALUE;
						res.send(result);
						} else {
							var query3 = new Object();
							var options = new Object();
							query3.$or = [
							              {cus_info : { _id : req.body.cus_id},status : status.ORDERSTATUS.CUSTOMERACCEPT.VALUE},
							              {cus_info : {_id : req.body.cus_id},status : status.ORDERSTATUS.WAITING.VALUE} 
							              ];
							options.skip = (req.body.page - 1) * 10;
							db.find(dataConfig.col_order,query3,options,function(err4,doc) {
								if (err4) {
									result.status = status.SYSTEMERROR.VALUE;
									res.send(result);
									} else {
										var maxPage = (doc.length - doc.length % 10) / 10 + 1;
										result.maxPage = maxPage;
										result.order_waiting_num = doc_waiting.length,
										result.order_success_num = doc_success.length;
										result.orders = doc;
										result.status = status.SUCCESS.VALUE;
										res.send(result);
										}
								});
							}
					});
				}
		});
	return next;
}
/*
 * @req.body: cus_id ,page {'cus_id': '1'}
 */
function showHisOrder(req, res, next) {
	var result = new Object();
	var query1 = new Object();
	query1.cus_info = new Object();
	query1.cus_info._id = req.body.cus_id;
	db
			.find(
					dataConfig.col_order,
					query1,
					function(err1, docs) {
						if (err1) {
							result.status = status.SYSTEMERROR.VALUE;
							res.send(result);
						} else {
							console.log('all doc is ' + JSON.stringify(docs));
							var count = 0;
							for ( var index in docs) {
								if (docs[index].status === status.ORDERSTATUS.CUSTOMERACCEPT.VALUE) {
									count++;
								}
							}
							result.order_history = new Array();
							var maxPage = (docs.length - docs.length % 10) / 10 + 1;
							var pageNumber = 10;
							if (maxPage == req.body.page) {
								pageNumber = docs.length % 10;
							}
							for ( var i = 0; i < pageNumber; i++) {
								result.order_history[i] = docs[(req.body.page - 1)
										* 10 + i];
							}
							result.maxPage = maxPage;
							result.succ_percent = count / docs.length;
							result.status = status.SUCCESS.VALUE;
							res.send(result);
						}
					});
	return next();
}

/*
 * cancel the order if the order is created. @path /cancelorder @req.body:
 * cus_id {'order_id': '1'}
 */

function cancelOrder(req, res, next) {
	var result = new Object();
	var selector = new Object();
	var document = new Object();

	selector.cus_id = req.body.cus_id;
	selector.stauts = {
		$ne : status.ORDERSTATUS.CUSTOMERACCEPT.VALUE
	};
	document.status = status.ORDERSTATUS.CANCEL.VALUE;
	db.find(dataConfig.col_driver, {}, {
		fields : {
			_id : 1
		}
	}, function(err1, userIds) {
		if (err1) {
			console.log(err1);
			result.status = status.SYSTEMERROR.VALUE;
			res.send(result);
		} else {
			var message = new Object();
			var notifi = new notification(userIds, message, function(err, req,
					res, data) {
				if (err) {
					console.log(err);
					result.status = status.SYSTEMERROR.VALUE;
					result.err = err;
					res.send(result);
				} else {
					console.log('notification is done!');
					db.update(dadaConfig.col_order, selector, document,
							function(err3, err4, doc) {
								if (err3||err4) {
									result.status = status.SYSTEMERROR.VALUE;
									res.send(result);
								} else {
									result.status = status.SUCCESS.VALUE;
									res.send(result);
								}
							});
				}
			});
		}
	});
	return next;
}

/*
 * @req.body cus_id setupTime fromAddrLat fromAddrLng toAddrLat toAddrLng
 * 
 * 
 */
function orderTaxi(req, res, next) {
	var result = new Object();
	var info = new Object();
	info.cus_id = req.body.cus_id;
	info.setupTime = req.body.setupTime;
	info.fromAddrLat = req.body.fromAddrLat;
	info.fromAddrLng = req.body.fromAddrLng;
	info.toAddrLat = req.body.toAddrLat;
	info.toAddrLng = req.body.toAddrLng;
	info.status = status.ORDERSTATUS.CUSTOMERREQUEST.VALUE;

	db.insert(dataConfig.col_order, info, function(err, doc) {
		if (err) {
			result.status = status.SYSTEMERROR.VALUE;
			res.send(result);
		} else {
			// send notification to the driver
			db.find(dataConfig.col_driver, {}, {
				fields : {
					_id : 1
				}
			}, function(err3, userIds) {
				if (err3) {
					result.status = status.SYSTEMERROR.VALUE;
					res.send(result);
				} else {
					var message = new Object();
					message.order = new Object();
					message.order = doc;
					var notifi = new notification(userIds, message, function(
							err, req, res, data) {
						if (err) {
							result.status = status.SYSTEMERROR.VALUE;
							res.send(result);
						} else {
							result.status = status.SUCCESS.VALUE;
							res.send(result);
						}
					});
				}
			});
		}
	});
	return next;
}
exports.services = [ bookNow, showOrder, showHisOrder, cancelOrder, orderTaxi ];